#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "lcd.h"
#include "fan.h"
#include "ble_server.h"
#include "ui_ctrl.h"


void app_main(void)
{
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    ESP_LOGI(__FUNCTION__ , "%d.",__LINE__);
    fan_task_init();
    ESP_LOGI(__FUNCTION__ , "%d.",__LINE__);
    ble_task_init();
    ESP_LOGI(__FUNCTION__ , "%d.",__LINE__);
    lcd_task_init();
    ESP_LOGI(__FUNCTION__ , "%d.",__LINE__);
    int cnt = 0;
    int event = 0;
    while(1)
    {
        if((event = ble_get_data_handler()) > 0)//不阻塞
        {
            lvgl_thread_lock();
            ESP_LOGI(__FUNCTION__ , "%d.event:%d.",__LINE__, event);
            if(event & BLE_STA_INIT_SUC)
            {
                const char* name = ble_get_device_name();
                ESP_LOGI(__FUNCTION__,"DEVICE_NAME:%s",name);
                //ui_set_device_name(name);
            }
            if (event & BLE_STA_CHANGE_DISCONN)
            {
                ui_set_fan_pwm_duty(0, 0);
                fan_set_duty(0,0);
                ui_screen_change_to(1);
            }
            if (event & BLE_STA_CHANGE_CONN)
            {
                ui_screen_change_to(2);
            }
            if (event & BLE_DAT_CHANGE_CPU_TEMP)
            {
                int t = ble_get_cpu_temperature();
                ui_set_cpu_temperature(t);
                ui_set_fan_pwm_duty(0, t);
                fan_set_duty(0,t);
            }
             lvgl_thread_unlock();
        }
        if(++cnt >= 100)
        {
            cnt = 0;
            lvgl_thread_lock();
            ui_set_fan_rpm(0,fan_get_rpm(0));
            lvgl_thread_unlock();
        }

        vTaskDelay(10 / portTICK_PERIOD_MS);
    }
}
